﻿

using System;
using AutoMapper;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;

using Oliving.Edge.AuthHelper;
using Oliving.Edge.Model;
using Oliving.Edge.Model.Models;
using Oliving.Edge.IServices;
using Oliving.Edge.Model.Dto;
using System.Linq.Expressions;
using Oliving.Edge.Common.Extensions;

namespace Oliving.Edge.Controllers
{
    [ApiController]
    [Route("api/Sys_DataDictionary")]
    [Authorize(Permissions.Name)]
    public class Sys_DataDictionaryController : OlivingControll
    {
        IMapper _mapper;
        private readonly ISys_DataDictionaryServices _Sys_DataDictionaryServices;
        private readonly ILogger<Sys_DataDictionaryController> _logger;

        private readonly IHttpContextAccessor _accessor;


        public Sys_DataDictionaryController(
                IHttpContextAccessor accessor, PermissionRequirement requirement,
                IMapper mapper, ILogger<Sys_DataDictionaryController> logger,
                ISys_DataDictionaryServices Sys_DataDictionaryServices
            ) : base(accessor, requirement)
        {
            _accessor = accessor;
            _logger = logger;
            _mapper = mapper;
            _Sys_DataDictionaryServices = Sys_DataDictionaryServices;
        }



        [HttpGet]
        [AllowAnonymous]
        [Route("/api/[controller]/Get")]
        public async Task<MessageModel<Sys_DataDictionaryDto>> Get(string id)
        {
            var data = new MessageModel<Sys_DataDictionaryDto>();
            Sys_DataDictionary model = await _Sys_DataDictionaryServices.QueryById(id);
            if (model == null)
            {
                data.response = null;
                data.msg = "数据不存在！";
                data.success = false;
            }
            else
            {
                var dto = _mapper.Map<Sys_DataDictionaryDto>(model);
                data.response = dto;
                data.msg = "获取成功！";
                data.success = true;
            }
            return data;
        }




        [HttpGet]
        [Route("/api/[controller]/GetPageList")]
        public async Task<MessageModel<PageModel<Sys_DataDictionaryPageDto>>> GetPageList(int page = 1, int PageSize = 20, string sidx = "", string order = "", string key = "")
        {
            Expression<Func<Sys_DataDictionary, bool>> whereExpression = _Sys_DataDictionary => true;


            if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key))
            {
                key = "";
            }
            else
            {
                //   whereExpression = whereExpression.And(d =>
                //           d.Canning_Car.Contains(key) 
                //       );
            }

            var data = await _Sys_DataDictionaryServices.QueryPageList(whereExpression, page, PageSize, sidx, order);

            return new MessageModel<PageModel<Sys_DataDictionaryPageDto>>()
            {
                msg = "获取成功",
                success = true,
                response = data
            };
        }



        /// <summary>
        /// 分页查下，根据父节点查下
        /// </summary>
        /// <param name="page"></param>
        /// <param name="PageSize"></param>
        /// <param name="sidx"></param>
        /// <param name="order"></param>
        /// <param name="key"></param>
        /// <param name="Pcode"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        [Route("/api/[controller]/GetPageListP")]
        public async Task<MessageModel<PageModel<Sys_DataDictionaryPageDto>>> GetPageListP(
            int page = 1, int PageSize = 20,
            string sidx = "", string order = "",
            string key = "",
            string Pcode = ""
            )
        {
            Expression<Func<Sys_DataDictionary, bool>> whereExpression = _Sys_DataDictionary => true;
            whereExpression = whereExpression.And(d => d.DD_ParentId == Pcode);

            //if (string.IsNullOrEmpty(Pcode) || string.IsNullOrWhiteSpace(Pcode))
            //{
            //    key = "";
            //}
            //else
            //{
            //    whereExpression = whereExpression.And(d =>     d.DD_ParentId== Pcode);
            //}

            var data = await _Sys_DataDictionaryServices.QueryPageList(whereExpression, page, PageSize, sidx, order);

            return new MessageModel<PageModel<Sys_DataDictionaryPageDto>>()
            {
                msg = "获取成功",
                success = true,
                response = data
            };
        }




        [HttpPut]
        [Route("/api/[controller]/Update")]
        public async Task<MessageModel<string>> Update([FromBody] Sys_DataDictionaryDto dto)
        {
            var data = new MessageModel<string>();

            if (dto != null && !string.IsNullOrEmpty(dto.DD_Id))
            {
                Sys_DataDictionary model = await _Sys_DataDictionaryServices.QueryById(dto.DD_Id);
                if (model != null)
                {
                    model.DD_ParentId = dto.DD_ParentId;
                    model.DD_Code = dto.DD_Code;
                    model.DD_Name = dto.DD_Name;
                    model.DD_Value = dto.DD_Value;
                    model.DD_QuickQuery = dto.DD_QuickQuery;
                    model.DD_SimpleSpelling = dto.DD_SimpleSpelling;
                    model.DD_IsDefault = dto.DD_IsDefault;
                    model.SortCode = dto.SortCode;
                    model.DeleteMark = dto.DeleteMark;
                    model.EnabledMark = dto.EnabledMark;
                    model.Description = dto.Description;
                    model.CreateDate = dto.CreateDate;
                    model.CreateUserId = dto.CreateUserId;
                    model.CreateUserName = dto.CreateUserName;
                    model.ModifyDate = dto.ModifyDate;
                    model.ModifyUserId = dto.ModifyUserId;
                    model.ModifyUserName = dto.ModifyUserName;

                    model.Modify(_accessor, "");
                    data.success = await _Sys_DataDictionaryServices.Update(model);

                    if (data.success)
                    {
                        data.msg = "更新成功";
                        data.response = dto.DD_Id.ObjToString();
                    }
                }
                else
                {
                    data.success = false;
                    data.msg = "参数异常，您要更新的数据不存在";
                }
            }
            else
            {
                data.success = false;
                data.msg = "参数异常";
            }
            return data;
        }





        [HttpPost]
        [Route("/api/[controller]/Add")]
        public async Task<MessageModel<string>> Add(Sys_DataDictionaryDto dto)
        {
            var data = new MessageModel<string>();

            Sys_DataDictionary model = _mapper.Map<Sys_DataDictionary>(dto);

            model.Create(_accessor);

            int id = await _Sys_DataDictionaryServices.AddGuid(model);

            data.success = id > 0;
            if (data.success)
            {
                data.response = id.ObjToString();
                data.msg = "添加成功";
            }
            return data;
        }




        [HttpDelete]
        [Route("/api/[controller]/Delete")]
        public async Task<MessageModel<string>> Delete(string id)
        {
            var data = new MessageModel<string>();
            if (!string.IsNullOrEmpty(id))
            {
                var userDetail = await _Sys_DataDictionaryServices.QueryById(id);
                userDetail.DeleteMark = 1; //?????????????

                data.success = await _Sys_DataDictionaryServices.Update(userDetail);
                if (data.success)
                {
                    data.msg = "删除成功";
                    data.response = userDetail?.DD_Id.ObjToString();
                }
            }
            return data;
        }





        [HttpDelete]
        [Route("/api/[controller]/BatchDelete")]
        public async Task<MessageModel<string>> BatchDelete(string ids)
        {
            var data = new MessageModel<string>();
            if (!string.IsNullOrEmpty(ids))
            {
                if (false)
                {
                    #region 软删除

                    int[] list = Array.ConvertAll<string, int>(ids.Split(','), s => int.Parse(s));

                    Sys_DataDictionary model = new Sys_DataDictionary();
                    //  model.C_State = -1;          ???????????????????
                    string whereStr = " DD_Id in (" + ids + ")";
                    List<string> colList = new List<string>();
                    //  colList.Add("C_State");    ???????????????????
                    List<string> colHL = new List<string>();

                    bool isOK = await _Sys_DataDictionaryServices.Update(model, colList, colHL, whereStr);

                    data.success = isOK;
                    if (data.success)
                    {
                        data.msg = "删除成功";
                        data.response = list.Count().ObjToString();
                    }

                    #endregion
                }
                {
                    #region 直接删除 

                    object[] list = Array.ConvertAll<string, object>(ids.Split(','), s => int.Parse(s));

                    bool isOK = await _Sys_DataDictionaryServices.DeleteByIds(list);

                    data.success = isOK;
                    if (data.success)
                    {
                        data.msg = "删除成功";
                        data.response = list.Count().ObjToString();
                    }
                    #endregion
                }
            }
            return data;
        }




    }
}

